package org.ezplatform.office.rd.common;

import cfca.sadk.org.bouncycastle.crypto.digests.GeneralDigest;
import cfca.sadk.org.bouncycastle.crypto.digests.SM3Digest;
import com.sansec.pqc.math.linearalgebra.ByteUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class SM3Util {

    /**
     * SM3加密方式之：不提供密钥的方式 SM3加密，返回加密后长度为64位的16进制字符串
     *
     * @param src 明文
     * @return
     */
    public static String encrypt(String src) {
        return ByteUtils.toHexString(getEncryptBySrcByte(src.getBytes()));
    }

    /**
     * 返回长度为32位的加密后的byte数组
     *
     * @param srcByte
     * @return
     */
    public static byte[] getEncryptBySrcByte(byte[] srcByte) {
        SM3Digest sm3 = new SM3Digest();
        sm3.update(srcByte, 0, srcByte.length);
        byte[] encryptByte = new byte[sm3.getDigestSize()];
        sm3.doFinal(encryptByte, 0);
        return encryptByte;
    }

    /**
     * 生成文件的SM3校验值
     *
     * @param file
     * @return
     * @throws
     */
    public static String getFileSM3String(File file) {
        InputStream fis;
        GeneralDigest digest = new SM3Digest();
        String resultHexString = "";
        try {
            fis = new FileInputStream(file);

            byte[] buffer = new byte[1024];
            int numRead = 0;
            while ((numRead = fis.read(buffer)) > 0) {
                digest.update(buffer, 0, numRead);
            }
            fis.close();
            byte[] hash = new byte[digest.getDigestSize()];

            digest.doFinal(hash, 0);
            resultHexString = ByteUtils.toHexString(hash);
        }catch (Exception e){
            e.printStackTrace();
        }

        return resultHexString;
    }

    public static void main(String[] args) throws Exception {
//        String srcStr = "（文件处理单）杨玉红的胡景铭手动归档.ofd";
        String path="D://Documents//225//ed0ca56869c340df8b3cea25c2445305.zip";
        File file=new File(path);
//        String hexStrNoKey = encrypt(srcStr);
        System.out.println(getFileSM3String(file));


//        System.out.println("(正文)杨玉红的胡景铭手动归档" + encrypt("(正文)杨玉红的胡景铭手动归档.ofd"));
//        System.out.println("（文件处理单）：" + encrypt("（文件处理单）杨玉红的胡景铭手动归档.ofd"));
//        System.out.println("(编辑稿)杨玉红的胡景铭手动归档：" + encrypt("(编辑稿)杨玉红的胡景铭手动归档.ofd"));
//        System.out.println("(附件1)演示文档.docx" + encrypt("(附件1)演示文档.docx"));
    }


}
